package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.Student;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.List;

public class EnrollmentDialog extends JDialog {
    private JComboBox<String> studentComboBox;
    private JComboBox<String> courseComboBox;
    private JButton saveButton;
    private JButton cancelButton;
    private boolean saved = false;
    private EnrollmentService enrollmentService = new EnrollmentService();
    private StudentService studentService = new StudentService();
    private CourseService courseService = new CourseService();
    private Enrollment enrollment;
    private List<Student> studentList;
    private List<Course> courseList;
    private Integer presetCourseId; // 预设的课程ID

    public EnrollmentDialog(Enrollment enrollment) {
        this.enrollment = enrollment;
        setTitle("选课登记");
        setModal(true);
        loadData();
        initComponents();
        setupLayout();
        setupListeners();
        if (enrollment != null) {
            fillForm(enrollment);
        }
        pack();
        setLocationRelativeTo(null);
    }
    
    /**
     * 创建带有预设课程ID的选课对话框
     * @param enrollment 选课记录，null表示新增
     * @param courseId 预设的课程ID
     */
    public EnrollmentDialog(Enrollment enrollment, Integer courseId) {
        this.enrollment = enrollment;
        this.presetCourseId = courseId;
        setTitle("选课登记");
        setModal(true);
        loadData();
        initComponents();
        setupLayout();
        setupListeners();
        
        if (enrollment != null) {
            fillForm(enrollment);
        } else if (courseId != null) {
            // 如果有预设的课程ID，则自动选择该课程
            for (int i = 0; i < courseList.size(); i++) {
                if (courseList.get(i).getId().equals(courseId)) {
                    courseComboBox.setSelectedIndex(i + 1); // +1 因为第一个是默认项
                    // 禁用课程选择，因为已经预设了课程
                    courseComboBox.setEnabled(false);
                    break;
                }
            }
        }
        
        pack();
        setLocationRelativeTo(null);
    }

    private void loadData() {
        studentList = studentService.getAllStudents();
        courseList = courseService.getAllCourses();
    }

    private void initComponents() {
        // 创建学生下拉框
        String[] studentNames = new String[studentList.size() + 1];
        studentNames[0] = "-- 请选择学生 --";
        for (int i = 0; i < studentList.size(); i++) {
            Student student = studentList.get(i);
            studentNames[i + 1] = student.getName() + " (" + student.getStudentId() + ")";
        }
        studentComboBox = new JComboBox<>(studentNames);
        
        // 创建课程下拉框
        String[] courseNames = new String[courseList.size() + 1];
        courseNames[0] = "-- 请选择课程 --";
        for (int i = 0; i < courseList.size(); i++) {
            Course course = courseList.get(i);
            courseNames[i + 1] = course.getName() + " (" + course.getCourseCode() + ")";
        }
        courseComboBox = new JComboBox<>(courseNames);
        
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");
    }

    private void setupLayout() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(6, 6, 6, 6);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        int row = 0;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("学生:"), gbc);
        gbc.gridx = 1; formPanel.add(studentComboBox, gbc); row++;
        
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(new JLabel("课程:"), gbc);
        gbc.gridx = 1; formPanel.add(courseComboBox, gbc); row++;

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        setLayout(new BorderLayout(10, 10));
        add(formPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupListeners() {
        saveButton.addActionListener(this::onSave);
        cancelButton.addActionListener(e -> dispose());
    }

    private void fillForm(Enrollment e) {
        // 设置学生选择
        if (e.getStudentId() != null) {
            for (int i = 0; i < studentList.size(); i++) {
                if (studentList.get(i).getId().equals(e.getStudentId())) {
                    studentComboBox.setSelectedIndex(i + 1); // +1 因为第一个是默认项
                    break;
                }
            }
        }
        
        // 设置课程选择
        if (e.getCourseId() != null) {
            for (int i = 0; i < courseList.size(); i++) {
                if (courseList.get(i).getId().equals(e.getCourseId())) {
                    courseComboBox.setSelectedIndex(i + 1); // +1 因为第一个是默认项
                    break;
                }
            }
        }
    }

    private void onSave(ActionEvent e) {
        int studentIndex = studentComboBox.getSelectedIndex();
        int courseIndex = courseComboBox.getSelectedIndex();
        
        if (studentIndex <= 0) {
            JOptionPane.showMessageDialog(this, "请选择学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (courseIndex <= 0) {
            JOptionPane.showMessageDialog(this, "请选择课程！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        Integer studentId = studentList.get(studentIndex - 1).getId();
        Integer courseId = courseList.get(courseIndex - 1).getId();
        
        // 检查是否已存在相同选课记录
        if (enrollmentService.checkDuplicateEnrollment(studentId, courseId)) {
            JOptionPane.showMessageDialog(this, "该学生已选择此课程！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (enrollment == null) {
            enrollment = new Enrollment();
        }
        
        enrollment.setStudentId(studentId);
        enrollment.setCourseId(courseId);
        enrollment.setEnrollmentDate(new Date());
        enrollment.setStatus("ACTIVE"); // 默认状态为"已选"
        
        boolean success;
        if (enrollment.getId() == null) {
            success = enrollmentService.insertEnrollment(enrollment);
        } else {
            success = enrollmentService.updateEnrollment(enrollment);
        }
        
        if (success) {
            saved = true;
            JOptionPane.showMessageDialog(this, "选课成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "选课失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public boolean isSaved() {
        return saved;
    }
} 